/* 
 * @(#)StringHelper.java    Created on 2013-3-14
 * Copyright (c) 2013 ZDSoft Networks, Inc. All rights reserved.
 * $Id$
 */
package com.hanbang.qzzds.utils.other;

import android.text.TextUtils;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串一些工具类
 *
 * @author xuan
 * @version $Revision: 1.0 $, $Date: 2013-3-14 下午8:20:55 $
 */
public class StringUtils {

    public static String getMoney(int money) {
        return money <= 0 ? "- -" : String.valueOf(money);
    }

    public static int getInt(String money) {
        try {
            int m = Integer.valueOf(money);
            return m;
        } catch (NumberFormatException e) {
            return -1;
        }

    }

    /**
     * 判断集合是否为空。
     */
    public static <T> boolean isEmpty(Collection<T> collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * 区空。
     */
    public static String trim(String str) {
        return str == null ? "" : str.trim();
    }

    /**
     * 是否绝对的空
     *
     * @return
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0 || str.equals("null"));
    }

    /**
     * 是否正常的字符串
     *
     * @return
     */
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

	/*
     * 比较两个字符串
	 */

    public static boolean isEquals(String actual, String expected) {
        return actual == expected
                || (actual == null ? expected == null : actual.equals(expected));
    }

    /*
     * 如果是绝对的空，就返回指定的文本
     */
    public static String nullStrToFormat(String str, String format) {
        return isBlank(str) ? format : str;
    }

    /*
     * 首字母大写
     */
    public static String capitalizeFirstLetter(String str) {
        if (isEmpty(str)) {
            return str;
        }

        char c = str.charAt(0);
        return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str
                : new StringBuilder(str.length())
                .append(Character.toUpperCase(c))
                .append(str.substring(1)).toString();
    }

    /*
     * 编码成utf-8
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(
                        "UnsupportedEncodingException occurred. ", e);
            }
        }
        return str;
    }

    /*
     * 获得超链接
     */
    public static String getHrefInnerHtml(String href) {
        if (isEmpty(href)) {
            return "";
        }

        String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
        Pattern hrefPattern = Pattern
                .compile(hrefReg, Pattern.CASE_INSENSITIVE);
        Matcher hrefMatcher = hrefPattern.matcher(href);
        if (hrefMatcher.matches()) {
            return hrefMatcher.group(1);
        }
        return href;
    }

    /*
     * 全角转半角
     */
    public static String fullWidthToHalfWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == 12288) {
                source[i] = ' ';
                // } else if (source[i] == 12290) {
                // source[i] = '.';
            } else if (source[i] >= 65281 && source[i] <= 65374) {
                source[i] = (char) (source[i] - 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /*
     * 半角转全角
     */
    public static String halfWidthToFullWidth(String s) {
        if (isEmpty(s)) {
            return s;
        }

        char[] source = s.toCharArray();
        for (int i = 0; i < source.length; i++) {
            if (source[i] == ' ') {
                source[i] = (char) 12288;
                // } else if (source[i] == '.') {
                // source[i] = (char)12290;
            } else if (source[i] >= 33 && source[i] <= 126) {
                source[i] = (char) (source[i] + 65248);
            } else {
                source[i] = source[i];
            }
        }
        return new String(source);
    }

    /**
     * bytes[]转换成Hex字符串,可用于URL转换，IP地址转换
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 字节转换成合适的单位
     *
     * @param value
     * @return
     */
    public static String prettyBytes(long value) {
        String args[] = {"B", "KB", "MB", "GB", "TB"};
        StringBuilder sb = new StringBuilder();
        int i;
        if (value < 1024L) {
            sb.append(String.valueOf(value));
            i = 0;
        } else if (value < 1048576L) {
            sb.append(String.format("%.1f", value / 1024.0));
            i = 1;
        } else if (value < 1073741824L) {
            sb.append(String.format("%.2f", value / 1048576.0));
            i = 2;
        } else if (value < 1099511627776L) {
            sb.append(String.format("%.3f", value / 1073741824.0));
            i = 3;
        } else {
            sb.append(String.format("%.4f", value / 1099511627776.0));
            i = 4;
        }
        sb.append(' ');
        sb.append(args[i]);
        return sb.toString();
    }


    /**
     * 判断View 的Text是否为空
     */
    public static boolean isEmpty(TextView textView) {
        if (textView != null && !TextUtils.isEmpty(textView.getText().toString().trim())) {
            return false;
        }
        return true;
    }

    /**
     * 判断Str是否为空，为空就返回指定的字符串
     */
    public static String isNullToConvert(String str, String convert) {
        return isBlank(str) ? convert : str;
    }

    /**
     * 判断Str是否为空，为空就返回指定的  "未知"
     */
    public static String isNullToConvert(String str) {
        return isBlank(str) ? "未知" : str;

    }

    /**
     * 非空判断处理和转换为String类型
     *
     * @param clz            主要对String,Integer,Double这三种类型进行处理
     * @param convertContent 要改的内容，这个要转换的内容可以不传，
     *                       1如传的是String类型就会认为String为空时要转换的内容，不传为空时默认转换为未知，
     *                       2如果传入的是intent类型，会认为double类型要保留的小数位数，
     *                       3如是传入的是0会认为double要取整
     * @return 把内容转换为String返回
     */
    public static String isNullToConvert(Object clz, Object... convertContent) {
        try {
            if (clz != null && !clz.toString().equals("null") && clz.toString().length() != 0) {
                if (clz instanceof String) {
                    return clz.toString().trim();
                } else if (clz instanceof Integer) {
                    return clz.toString();
                } else if (clz instanceof Double) {
                    BigDecimal bd = new BigDecimal(Double.parseDouble(clz.toString()));
                    if (convertContent != null && convertContent.length != 0 && convertContent[0] instanceof Integer) {
                        int i = Integer.parseInt(convertContent[0].toString());
                        if (i == 0) {
                            String str = String.valueOf(Math.floor(Double.parseDouble(clz.toString())));
                            return str.contains(".") ? str.substring(0, str.indexOf(".")) : str;
                        } else {
                            return String.valueOf(bd.setScale(Math.abs(i), BigDecimal.ROUND_DOWN).doubleValue());
                        }
                    }
                    return String.valueOf(bd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
                } else {
                    return clz.toString();
                }
            }
            if (convertContent != null && convertContent.length != 0) {
                return convertContent[0].toString();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "未知";
    }

    /**
     * 判断Str是否为空，为空就返回指定的  "未知"
     */
    public static String isNullToConvert(String str, int maxLenght) {
        return isBlank(str) ? "未知" : str.substring(0, str.length() < maxLenght ? str.length() : maxLenght);

    }

    /**
     * 判断Str是否为空，为空就返回指定的字符串  并加上指定的前缀
     */
    public static String isNullToConvertQian(String str, String convert, String qian) {
        return isBlank(str) ? qian + convert : qian + str;

    }

    /**
     * 判断Str是否为空，为空就返回指定的字符串  并加上指定的后缀
     */
    public static String isNullToConvertHou(String str, String convert, String hou) {
        return isBlank(str) ? convert + hou : str + hou;

    }


    /**
     * 小数 四舍五入 19.0->19.0    返回Double
     */

    public static Double roundDouble(double val, int precision) {
        int resQ = (int) Math.round(val * Math.pow(10.0, precision));
        double res = resQ / Math.pow(10.0, precision);
        return res;
    }

    /**
     * 小数后两位
     *
     * @param val
     * @return
     */
    public static Double roundDouble(double val) {
        int resQ = (int) Math.round(val * Math.pow(10.0, 2));
        double res = resQ / Math.pow(10.0, 2);
        return res;
    }

    /**
     * 小数 四舍五入 19.0->19.0   返回字符串
     */

    public static String roundString(double val, int precision) {
        return String.valueOf(roundDouble(val, precision));

    }


    /*
     * html 获取纯文本
     */
    public static String Html2Text(String inputString) {

        if (inputString == null || inputString.trim().equals("")) {
            return "";
        }

        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        Matcher m_script;
        Pattern p_style;
        Matcher m_style;
        Pattern p_html;
        Matcher m_html;

        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            // }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            // }
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            textStr = htmlStr;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return textStr;// 返回文本字符串
    }

    /**
     * 将Excepiton信息转换成String字符串.
     *
     * @return
     */
    public static String exceptionToString(Throwable throwable) {
        if (throwable == null) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            throwable.printStackTrace(new PrintStream(baos));
        } finally {
            try {
                baos.close();
            } catch (Exception ex) {
                ex.printStackTrace();
                System.gc();
            }
        }
        return baos.toString();
    }

    /**
     * unicode转UTF-8
     */
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }


    public static String getUrlToFileName(String url) {
        String res = null;
        if (url != null) {
            String[] ress = url.split("/");
            if (ress.length > 0) {
                res = ress[ress.length - 1];
            }
        }
        return res;
    }




    /**
     * 把过程图片，转换成集合
     *
     * @param str
     * @return
     */
    public static ArrayList<String> transitionPicture(String str) {
        ArrayList<String> list = new ArrayList();

        try {
            //把过程图片截取成数组
            if (!StringUtils.isBlank(str) && str.contains(",")) {
                String[] array = str.split(",");

                for (int i = 0; i < array.length; i++) {
                    list.add( array[i]);
                }
            }

            return list;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }





}
